<template>
  <div class="contentView" v-loading="formLoading" :style="`height:${contentHeight}px`">
    <div class="btnWrap routeHeader">
      <div>
        <el-button @click="saveData" type="primary" v-hasPermi="['order:product-pelation:save']" :disabled="disabled">保存</el-button>
        <el-button @click="submitData" type="primary" v-hasPermi="['order:product-pelation:submit']" :disabled="disabled">提交</el-button>
        <el-button @click="close">关闭</el-button>
      </div>
    </div>
    <el-scrollbar :style="`height:${contentHeight - 60}px`">
      <el-table v-loading="loading" :data="list" border>
        <el-table-column type="index" width="55" label="序号" align="left" fixed="left"/>
        <!-- 列定义 -->
        <el-table-column label="订单号" align="left" width="180" :class="'custom-header'">
          <template #default="scope">
            <el-select
              v-model="scope.row.orderNumber"
              placeholder="请选择订单编号"
              filterable
              remote
              :remote-method="filterOptions"
              @change="handleChange"
              :disabled="route.query.type == 'update'"
            >
              <el-option
                v-for="(dict, index) in filteredOptions"
                :key="index"
                :label="dict.orderNumber"
                :value="dict.orderNumber"
              />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="订单类型" align="left" width="180">
          <template #default="scope">
            <dict-tag :type="DICT_TYPE.MARKET_ORDER_TYPE" :value="scope.row.dictOrderType" />
          </template>
        </el-table-column>
        <el-table-column label="业务类型" align="left" width="180">
          <template #default="scope">
            <dict-tag :type="DICT_TYPE.BUSINESS_TYPE" :value="scope.row.dictBusinessType" />
          </template>
        </el-table-column>
        <el-table-column label="销售类型" align="left" width="180">
          <template #default="scope">
            <dict-tag :type="DICT_TYPE.SALE_TYPE" :value="scope.row.dictSaleType" />
          </template>
        </el-table-column>
        <el-table-column label="客户简称" align="left" width="180">
          <template #default="scope">
            {{ scope.row.customerName }}
          </template>
        </el-table-column>
        <el-table-column label="客户代码" align="left" width="180">
          <template #default="scope">
            {{ scope.row.customerCode }}
          </template>
        </el-table-column>
        <el-table-column label="销售部门" align="left" width="180">
          <template #default="scope">
            {{ scope.row.salesDepartment }}
          </template>
        </el-table-column>
        <el-table-column label="合同日期" align="left" width="180">
          <template #default="scope">
            {{ scope.row.contractDate }}
          </template>
        </el-table-column>
        <el-table-column label="订单日期" align="left" width="180">
          <template #default="scope">
            {{ scope.row.orderDate }}
          </template>
        </el-table-column>
        <el-table-column label="业务员" align="left" width="180">
          <template #default="scope">
            {{ scope.row.salesperson }}
          </template>
        </el-table-column>
        <el-table-column label="税率" align="left" width="180">
          <template #default="scope">
            {{ scope.row.taxRate }}
          </template>
        </el-table-column>
        <el-table-column label="汇率" align="left" width="180">
          <template #default="scope">
            {{ scope.row.exchangeRate }}
          </template>
        </el-table-column>
        <el-table-column label="付款条件" align="left" width="180">
          <template #default="scope">
            {{ scope.row.paymentConditions }}
          </template>
        </el-table-column>
        <el-table-column label="商务合同" align="left" width="180">
          <template #default="scope">
            <span style="cursor: pointer" @click="downFile(scope.row.filePath)">
              {{ scope.row.fileName }}</span
            >
          </template>
        </el-table-column>
        <el-table-column label="备注" align="left" width="180">
          <template #default="scope">
            {{ scope.row.remark }}
          </template>
        </el-table-column>
        <el-table-column label="创建人" align="left" width="180">
          <template #default="scope">
            {{ scope.row.creatorName }}
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="left" width="180">
          <template #default="scope">
            {{ scope.row.createTime }}
          </template>
        </el-table-column>
        <el-table-column label="变更人" align="left" width="180">
          <template #default="scope">
            {{ scope.row.orderChangePerson }}
          </template>
        </el-table-column>
        <el-table-column label="变更时间" align="left" width="180">
          <template #default="scope">
            {{ scope.row.orderChangeDate }}
          </template>
        </el-table-column>
      </el-table>
      <div class="btnWraps">
        <el-button @click="addRow" type="primary">新增行</el-button>
      </div>
      <el-table v-loading="loading" :data="listPro" border style="margin-top: 10px">
        <el-table-column type="index" width="55" label="序号" align="left" fixed="left" />
        <!-- 列定义 -->
        <el-table-column align="left" width="180" :class="'custom-header'">
          <template #header>
            <span style="color: red" v-if="isDisabled">*</span>
            <span>产品编号</span>
          </template>
          <template #default="scope">
            <div class="select-wrapper">
              <el-select
                v-model="scope.row.productNumber"
                placeholder="请选择产品编号"
                class="!w-140px"
                filterable
                remote
                :remote-method="filterOptions1"
                @change="handleChangePd(scope.$index)"
              >
                <el-option
                  v-for="channel in filteredOptions1"
                  :key="channel.productNumber"
                  :value="channel.productNumber"
                  :label="channel.productNumber"
                />
              </el-select>
              <span class="search-icon" @click="handleSearch(scope.$index)">
                <Icon icon="ep:search" />
              </span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="产品名称" align="left" width="180">
          <template #default="scope">
            <el-input
              v-nextInput="'productName'"
              name="productName"
              v-model="scope.row.productName"
              :disabled="isDisabled"
              placeholder="请输入产品名称"
            />
          </template>
        </el-table-column>
        <el-table-column label="产品规格" align="left" width="180">
          <template #default="scope">
            <el-input
              v-nextInput="'productStandard'"
              name="productStandard"
              v-model="scope.row.productStandard"
              :disabled="isDisabled"
              placeholder="请输入产品规格"
            />
          </template>
        </el-table-column>
        <el-table-column align="left" width="180">
          <template #header>
            <span style="color: red">*</span>
            <span>单位</span>
          </template>
          <template #default="scope">
            <el-input
              v-nextInput="'partUnit'"
              name="partUnit"
              v-model="scope.row.partUnit"
              placeholder="请输入单位"
            />
          </template>
        </el-table-column>
        <el-table-column label="订单数量" align="left" width="180">
          <template #header>
            <span style="color: red">*</span>
            <span>订单数量</span>
          </template>
          <template #default="scope">
            <el-input
              v-nextInput="'orderQuantity'"
              name="orderQuantity"
              v-model="scope.row.orderQuantity"
              :disabled="scope.row.editable"
              type="number"
              :min="0"
              :input-filter="filterNumber"
              placeholder="请输入订单数量"
            />
          </template>
        </el-table-column>
        <el-table-column label="发货日期" align="left" width="180">
          <template #header>
            <span style="color: red">*</span>
            <span>发货日期</span>
          </template>
          <template #default="scope">
            <el-date-picker
              v-model="scope.row.deliveryDate"
              type="date"
              placeholder="请选择发货日期"
              style="width: 150px"
              value-format="YYYY-MM-DD"
            />
          </template>
        </el-table-column>
        <el-table-column label="" align="left" width="180">
          <template #header>
            <span style="color: red">*</span>
            <span>交货项目类型</span>
          </template>
          <template #default="scope">
            <el-select v-model="scope.row.dictDeliveryProjectType" placeholder="请选择交货项目类型">
              <el-option
                v-for="(dict, index) in getIntDictOptions(DICT_TYPE.DELIVERY_PROJECT_TYPE)"
                :key="index"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="" align="right" width="180">
          <template #header>
            <span style="color: red">*</span>
            <span>报价</span>
          </template>
          <template #default="scope">
            <el-input
              v-nextInput="'quotation'"
              name="quotation"
              v-model="scope.row.quotation"
              :disabled="scope.row.editable"
              placeholder="请输入报价"
              type="number"
              :min="0"
            />
          </template>
        </el-table-column>
        <el-table-column label="" align="right" width="180">
          <template #header>
            <span style="color: red">*</span>
            <span>含税单价</span>
          </template>
          <template #default="scope">
            <el-input
              v-nextInput="'priceTaxTotal'"
              name="priceTaxTotal"
              v-model="scope.row.priceTaxTotal"
              :disabled="scope.row.editable"
              input-filter="number"
              type="number"
              :min="0"
              placeholder="请输入含税单价"
            />
          </template>
        </el-table-column>
        <el-table-column align="right" width="180">
          <template #header>
            <span style="color: red">*</span>
            <span>价税合计</span>
          </template>
          <template #default="scope">
            <el-input
              v-nextInput="'taxIncludedPrice'"
              name="taxIncludedPrice"
              v-model="scope.row.taxIncludedPrice"
              :disabled="scope.row.editable"
              type="number"
              :min="0"
              :max="100"
              placeholder="请输入价税合计"
            />
          </template>
        </el-table-column>
        <el-table-column align="left" width="180">
          <template #header>
            <span style="color: red">*</span>
            <span>税率</span>
          </template>
          <template #default="scope">
            <el-input
              v-nextInput="'taxRate'"
              name="taxRate"
              v-model="scope.row.taxRate"
              :disabled="scope.row.editable"
              placeholder="请输入税率"
              :min="0"
              :max="100"
            />
          </template>
        </el-table-column>
        <el-table-column label="状态" align="left" width="180">
          <template #default="scope">
            <dict-tag :type="DICT_TYPE.MARKET_ORDER_STATUS" :value="scope.row.dictStatus" />
          </template>
        </el-table-column>
        <el-table-column label="备注" align="left" width="180">
          <template #default="scope">
            <el-input
              v-nextInput="'remark'"
              name="remark"
              v-model="scope.row.remark"
              :disabled="scope.row.editable"
              placeholder="请输入备注"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" align="left" min-width="110" fixed="right">
          <template #default="scope">
            <!-- 删除按钮 -->
            <el-button link type="danger" @click="deleteRow(scope.$index)">删除行</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-scrollbar>
  </div>
  <!-- 客户档案列表 -->
  <CustomerProfile ref="formRef" @success="addData" />
</template>

<script lang="ts" setup>
import { useRoute } from 'vue-router'
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import * as productRelationApi from '@/api/orderManagement/productRelation'
import { useTagsViewStore } from '@/store/modules/tagsView'
import CustomerProfile from './customerProfile.vue'
const disabled = ref(false)
const isDisabled = ref(false)
const tagsViewStore = useTagsViewStore()
const routes = useRouter() // 路由
const route = useRoute()
const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const { push } = useRouter()
const loading = ref(true)
const formLoading = ref(false)
let title = ref('新增产品')
let list = ref<any>([])
let listPro = ref<any>([])
let listOption = ref<any>([])
let filteredOptions = ref<any>([])
let filteredOptions1 = ref<any>([])

//模糊查询
const filterOptions = async (query) => {
  filteredOptions = await listOption.filter((option) => option.orderNumber.includes(query))
}
//模糊查询
const filterOptions1 = async (query) => {
  if (query) {
    filteredOptions1 = await tenantOptions.value.filter((option) =>
      option.productNumber.includes(query)
    )
  }
}
//获取订单号下拉选择器选中的值
const handleChange = async (value) => {
  for (let i = 0; i < listOption.length; i++) {
    if (listOption[i].orderNumber == value) {
      let data = await listOption[i]
      list.value[0].dictOrderType = data.dictOrderType
      list.value[0].dictBusinessType = data.dictBusinessType
      list.value[0].dictSaleType = data.dictSaleType
      list.value[0].customerName = data.customerName
      list.value[0].customerCode = data.customerCode
      list.value[0].salesDepartment = data.salesDepartment
      list.value[0].contractDate = data.contractDate
      list.value[0].orderDate = data.orderDate
      list.value[0].salesperson = data.salesperson
      list.value[0].taxRate = data.taxRate
      list.value[0].exchangeRate = data.exchangeRate
      list.value[0].paymentConditions = data.paymentConditions
      list.value[0].dictChangeType = data.dictChangeType
      list.value[0].version = data.version
      list.value[0].orderChangePerson = data.orderChangePerson
      list.value[0].orderChangeDate = data.orderChangeDate
      list.value[0].remark = data.remark
      list.value[0].businessContractUrl = data.businessContractUrl
      list.value[0].businessContractName = data.businessContractName
      list.value[0].dictOrderStatus = data.dictOrderStatus
      list.value[0].orderId = data.id
      list.value[0].filePath = data.filePath
      list.value[0].fileName = data.fileName
      list.value[0].creatorName = data.creatorName
      list.value[0].createTime = data.createTime
      filteredOptions = listOption
      if (data.dictOrderType == 50) {
        isDisabled.value = false
      } else {
        isDisabled.value = true
      }
    }
  }
}
const filterNumber = (value) => {
  return value.replace(/[^0-9]/g, '')
}
const tenantOptions = ref<any>([])
const getList = async () => {
  loading.value = true
  try {
    // 请求数据的逻辑
  } finally {
    loading.value = false
  }
}
const addRowDD = () => {
  const newRow = {
    orderNumber: undefined,
    dictOrderType: undefined,
    dictBusinessType: undefined,
    dictSaleType: undefined,
    customerName: undefined,
    customerCode: undefined,
    salesDepartment: undefined,
    contractDate: undefined,
    orderDate: undefined,
    salesperson: undefined,
    taxRate: undefined,
    exchangeRate: undefined,
    paymentConditions: undefined,
    dictChangeType: undefined,
    version: undefined,
    orderChangePerson: undefined,
    orderChangeDate: undefined,
    remark: undefined,
    businessContractUrl: undefined,
    businessContractName: undefined,
    dictOrderStatus: undefined,
    orderId: undefined,
    attachmentUrl: '',
    attachmentName: ''
  }
  list.value.push(newRow)
}

const addRow = () => {
  if (list.value[0].dictOrderType == 50) {
    isDisabled.value = false
  } else {
    isDisabled.value = true
  }
  if (list.value[0].orderNumber) {
    const newRow = {
      productNumber: undefined, //产品编号
      orderQuantity: undefined, //订单数量
      deliveryDate: undefined, //发货日期
      dictDeliveryProjectType: 1, //交货项目类型
      quotation: undefined, //报价
      priceTaxTotal: undefined, //含税单价
      taxIncludedPrice: undefined, //价税合计
      productName: undefined,
      taxRate: undefined, //税率
      productStandard: undefined,
      remark: undefined,
      partUnit: undefined,
      dictStatus: undefined //状态
    }
    listPro.value.push(newRow)
  } else {
    message.warning(t('订单号不能为空'))
  }
}

const deleteRow = (index: number) => {
  listPro.value.splice(index, 1)
}
const formRef = ref()
//搜索图标
const handleSearch = async (index) => {
  formRef.value.open(index, listPro.value[index].productNumber)
}
const handleChangePd = (index) => {
  for (let i = 0; i < tenantOptions.value.length; i++) {
    if (tenantOptions.value[i].productNumber == listPro.value[index].productNumber) {
      listPro.value[index].productName = tenantOptions.value[i].productName
      listPro.value[index].productStandard = tenantOptions.value[i].productStandard
      listPro.value[index].partUnit = tenantOptions.value[i].partUnit
    }
  }
}
const addData = async (data) => {
  listPro.value[data.index.value].productNumber = data.list[0].productNumber
  listPro.value[data.index.value].productName = data.list[0].productName
  listPro.value[data.index.value].productStandard = data.list[0].productStandard
  listPro.value[data.index.value].partUnit = data.list[0].partUnit
}
//必填校验
const check = async () => {
  let data = await listPro.value
  if (data.length > 0) {
    for (let i = 0; i < data.length; i++) {
      if (list.value[0].dictOrderType == 50) {
        if (!data[i].productName) {
          message.warning(t('产品名称不能为空'))
          return false
        }
      }

      if (!data[i].partUnit) {
        message.warning(t('单位不能为空'))
        return false
      }
      if (!data[i].orderQuantity) {
        message.warning(t('订单数量不能为空'))
        return false
      }
      if (!data[i].deliveryDate) {
        message.warning(t('发货日期不能为空'))
        return false
      }
      if (!data[i].dictDeliveryProjectType) {
        message.warning(t('交货项目类型不能为空'))
        return false
      }

      if (
        data[i].quotation === '' ||
        data[i].quotation === undefined ||
        data[i].quotation === null
      ) {
        message.warning(t('报价不能为空'))
        return false
      }
      if (
        data[i].priceTaxTotal === '' ||
        data[i].priceTaxTotal === undefined ||
        data[i].priceTaxTotal === null
      ) {
        message.warning(t('含税单价不能为空'))
        return false
      }
      if (
        data[i].taxIncludedPrice === '' ||
        data[i].taxIncludedPrice === undefined ||
        data[i].taxIncludedPrice === null
      ) {
        message.warning(t('含税计价不能为空'))
        return false
      }
      if (data[i].taxRate === '' || data[i].taxRate === null || data[i].taxRate === undefined) {
        message.warning(t('税率不能为空'))
        return false
      }
      if (data[i].dictDeliveryProjectType == 1) {
        if (
          data[i].quotation <= 0 ||
          data[i].quotation == '' ||
          data[i].priceTaxTotal <= 0 ||
          data[i].priceTaxTotal == '' ||
          data[i].taxIncludedPrice <= 0 ||
          data[i].taxIncludedPrice == ''
        ) {
          message.warning(t('交货项目类型为有偿,价格不能为0,也不能为空'))
          return false
        }
      } else {
        if (data[i].quotation != 0 || data[i].priceTaxTotal != 0 || data[i].taxIncludedPrice != 0) {
          message.warning(t('交货项目类型为无偿,价格应该为0'))
          return false
        }
      }
    }
  } else {
    message.warning(t('至少新增一行'))
    return false
  }

  return true
}
/**保存 */
const saveData = async () => {
  try {
    const isFlag = await check()
    if (isFlag) {
      disabled.value = true
      let type = route.query.type
      if (type === 'create') {
        let reqData = list.value[0]
        if (reqData.dictOrderType == 50) {
          reqData.orderId = reqData.orderId
          reqData.submitFlag = 1
          reqData.products = listPro.value
          await productRelationApi.createProductRelation(reqData)
          message.success(t('common.createSuccess'))
          tagsViewStore.delView(routes.currentRoute.value)
          push('/orderManagement/orderManagement/marketing/productionInfo')
          disabled.value = false
        } else {
          if (reqData.orderNumber) {
            reqData.orderId = reqData.orderId
            reqData.submitFlag = 1
            reqData.products = listPro.value
            await productRelationApi.createProductRelation(reqData)
            message.success(t('common.createSuccess'))
            tagsViewStore.delView(routes.currentRoute.value)
            push('/orderManagement/orderManagement/marketing/productionInfo')
            disabled.value = false
          } else {
            message.warning('订单号不能为空')
            disabled.value = false
          }
        }
      } else {
        let reqData = list.value[0]
        reqData.orderId = reqData.orderId
        reqData.submitFlag = 1
        reqData.products = listPro.value
        await productRelationApi.createProductRelation(reqData)
        message.success(t('common.updateSuccess'))
        tagsViewStore.delView(routes.currentRoute.value)
        push('/orderManagement/orderManagement/marketing/productionInfo')
        disabled.value = false
      }
    }
    disabled.value = false
  } finally {
    disabled.value = false
  }
}
/**提交 */
const submitData = async () => {
  try {
    const isFlag = await check()
    if (isFlag) {
      loading.value = true
      try {
        disabled.value = true
        let type = route.query.type
        if (type === 'create') {
          let reqData = list.value[0]
          if (reqData.dictOrderType == 50) {
            reqData.orderId = reqData.orderId
            reqData.submitFlag = 2
            reqData.products = listPro.value
            await productRelationApi.createProductRelation(reqData)
            message.success(t('common.createSuccess'))
            tagsViewStore.delView(routes.currentRoute.value)
            push('/orderManagement/orderManagement/marketing/productionInfo')
            disabled.value = false
          } else {
            if (reqData.orderNumber) {
              reqData.orderId = reqData.orderId
              reqData.submitFlag = 2
              reqData.products = listPro.value
              await productRelationApi.createProductRelation(reqData)
              message.success(t('common.createSuccess'))
              tagsViewStore.delView(routes.currentRoute.value)
              push('/orderManagement/orderManagement/marketing/productionInfo')
              disabled.value = false
            } else {
              message.warning('订单号不能为空')
              disabled.value = false
            }
          }
        } else {
          let reqData = list.value[0]
          reqData.orderId = reqData.orderId
          reqData.submitFlag = 2
          reqData.products = listPro.value
          await productRelationApi.createProductRelation(reqData)
          message.success(t('common.updateSuccess'))
          tagsViewStore.delView(routes.currentRoute.value)
          push('/orderManagement/orderManagement/marketing/productionInfo')
          disabled.value = false
        }
      } finally {
        loading.value = false
      }
    }
  } finally {
    disabled.value = false
  }
}
/**关闭 */
const close = () => {
  tagsViewStore.delView(routes.currentRoute.value)
  push('/orderManagement/orderManagement/marketing/productionInfo')
}
//获取产品信息
const getDetail = async (orderNumber) => {
  list.value = []
  const data = await productRelationApi.getDetailProductRelation(orderNumber)
  list.value[0] = data
  listPro.value = data.products
}
//获取订单信息列表
const getproductRelationAll = async () => {
  let params = {
    dictOrderStatus: '20',
    isQuote: '1',
    orderNumber: ''
  }
  const data = await productRelationApi.getProductRelationPageAll(params)
  listOption = data.list
  filteredOptions = data.list
}
const downFile = (value) => {
  window.open(value)
}
const contentHeight = ref(0)
const refreshData = async () => {
  formLoading.value = true
  contentHeight.value = document.body.clientHeight - 127
  formLoading.value = false
}
//获取客户档案列表
const getProductsList = async () => {
  let params = {}
  const data = await productRelationApi.getProductsList(params)
  tenantOptions.value = data.list
}
// 初始化
onMounted(async () => {
  refreshData()
  let type = route.query.type
  if (type === 'create') {
    title.value = '新增产品'
    await addRowDD()
  } else {
    title.value = '编辑产品'
    getDetail(route.query.orderNumber)
  }
  await getproductRelationAll()
  await getList()

  await getProductsList()
})
</script>
<style lang="scss" scoped>
.btnWrap {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
}
.btnWraps {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
  margin-top: 10px;
}
.el-table .custom-header::before {
  content: '*';
  color: red;
  margin-right: 4px; /* 根据需要调整小红星与字段的位置 */
}
.contentView {
  padding: 10px;
  background: #fff;
}
.tableView {
  :deep(.el-input__wrapper) {
    box-shadow: 0 0 0 0px var(--el-input-border-color, var(--el-border-color)) inset;
    cursor: default;
    .el-input__inner {
      cursor: default !important;
      text-align: center;
    }
  }
}
.select-wrapper {
  display: flex;
  align-items: center;
}

.search-icon {
  margin-left: -24px; /* 这里的 -24px 是根据 Icon 的宽度进行调整的 */
  cursor: pointer;
  margin-top: 5px;
}
</style>
